package org.dxy.infrastructure.persistent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dxy.infrastructure.persistent.po.query.MBOMViewPo;
import org.dxy.infrastructure.persistent.mapper.MBOMViewMapper;
import org.dxy.infrastructure.persistent.service.MBOMViewService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * MBOM视图服务实现
 * @author dxy
 * @createTime 2025/9/10
 */
@Service
public class MBOMViewServiceImpl extends ServiceImpl<MBOMViewMapper, MBOMViewPo> implements MBOMViewService {

    @Override
    public long countByProductId(Long productId) {
        if (productId == null) {
            return 0;
        }
        return count(new LambdaQueryWrapper<MBOMViewPo>()
                .eq(MBOMViewPo::getProductId, productId));
    }

    @Override
    public boolean existsByMbomCode(String mbomCode) {
        if (mbomCode == null || mbomCode.trim().isEmpty()) {
            return false;
        }
        return lambdaQuery()
                .eq(MBOMViewPo::getMbomCode, mbomCode)
                .exists();
    }

    @Override
    public List<MBOMViewPo> getByProductId(Long productId) {
        if (productId == null) {
            return List.of();
        }
        return list(new LambdaQueryWrapper<MBOMViewPo>()
                .eq(MBOMViewPo::getProductId, productId)
                .orderByDesc(MBOMViewPo::getCreatedTime));
    }

    @Override
    public List<MBOMViewPo> getByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            return List.of();
        }
        return list(new LambdaQueryWrapper<MBOMViewPo>()
                .eq(MBOMViewPo::getStatus, status)
                .orderByDesc(MBOMViewPo::getCreatedTime));
    }

    @Override
    public List<MBOMViewPo> getByProductIdAndStatus(Long productId, String status) {
        if (productId == null || status == null || status.trim().isEmpty()) {
            return List.of();
        }
        return list(new LambdaQueryWrapper<MBOMViewPo>()
                .eq(MBOMViewPo::getProductId, productId)
                .eq(MBOMViewPo::getStatus, status)
                .orderByDesc(MBOMViewPo::getCreatedTime));
    }

    @Override
    public MBOMViewPo getLatestVersionByProductId(Long productId) {
        if (productId == null) {
            return null;
        }
        return getOne(new LambdaQueryWrapper<MBOMViewPo>()
                .eq(MBOMViewPo::getProductId, productId)
                .orderByDesc(MBOMViewPo::getVersion)
                .last("LIMIT 1"));
    }
}